import React from 'react'
import { connect } from 'react-redux'
import { messages, deepCopy } from 'share/common'
import { Form, Table, Button, Select } from 'antd'
const Option = Select.Option;

import baseService from 'share/base.service'
import RSService from 'containers/setting/role-setting/role-setting.service'
import 'styles/setting/role-setting/finance-role/finance-role-detail.scss'
import ResizeTable from "components/resize-table";

class DetailPageAuth extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      columns: [],
      defaultData: [
        {first: {pageName: 'FINANCEMANAGEMENT', label: messages('setting.key907'/*财务管理*/), action: 0},
          second: {pageName: 'EXPENSEAUDIT', label: messages('setting.key908'/*单据审核*/), action: 0}},
        {second: {pageName: 'RECEIPTEDINVOICES', label: messages('setting.key909'/*待开票*/), action: 0}},
        {second: {pageName: 'VENDORRECONCILIATION', label: messages('setting.key910'/*供应商对账*/), action: 0}},
        {second: {pageName: 'LOANMANAGEMENT', label: messages('setting.key911'/*借还款管理*/), action: 0},
          third: {pageName: 'LOANGLOBALVIEW', label: messages('setting.key912'/*全局查看*/), action: 0}},
        {third: {pageName: 'REPAYMENTSLIPMANAGEMENT', label: messages('setting.key913'/*还款单管理*/), action: 0}},
        {third: {pageName: 'LOANBILLMANAGEMENT', label: messages('setting.key914'/*借款单管理*/), action: 0}},
        {third: {pageName: 'RESTAURANTLOANANDREPAYVIEW', label: messages('setting.key2831'/*餐厅借还款全局查看*/), action: 0}},
        {second: {pageName: 'VENDORMAINTENANCE', label: messages('setting.key915'/*供应商维护*/), action: 0}},
        {second: {pageName: 'EXPENSEVIEW', label: messages('setting.key916'/*单据查看*/), action: 0}},
        {second: {pageName: 'PRINTINVOICEBATCH', label: messages('setting.key917'/*批量打印电子票*/), action: 0}},
        {second: {pageName: 'EXPENSEAPPLICATIONVIEW', label: messages('setting.key918'/*费用申请查看*/), action: 0}},
        {first: {pageName: 'BUDGET', label: messages('setting.key919'/*预算*/), action: 0},
          second: {pageName: 'BUDGETJOURNAL', label: messages('setting.key920'/*预算日记帐*/), action: 0}},
        {second: {pageName: 'BUDGETJOURNALREVIEW', label: messages('setting.key921'/*预算日记账复核*/), action: 0}},
        {second: {pageName: 'BUDGETAMOUNT', label: messages('setting.key922'/*预算余额*/), action: 0}},
        {second: {pageName: 'BUDGETBALANCEPLANINQUIRY', label: messages('setting.key923'/*预算余额方案查询*/), action: 0}},
        {second: {pageName: 'BUDGETOCCUPANCYADJUSTMENT', label: messages('setting.key924'/*预算占用调整*/), action: 0}}
      ],
      data: [],
      defaultPageRoles: [
        {pageName: 'FINANCEMANAGEMENT', action: 0},
        {pageName: 'EXPENSEAUDIT', action: 0},
        {pageName: 'RECEIPTEDINVOICES', action: 0},
        {pageName: 'VENDORRECONCILIATION', action: 0},
        {pageName: 'EXPENSEPAYMENT', action: 0},
        {pageName: 'LOANMANAGEMENT', action: 0},
        {pageName: 'LOANGLOBALVIEW', action: 0},
        {pageName: 'REPAYMENTSLIPMANAGEMENT', action: 0},
        {pageName: 'LOANBILLMANAGEMENT', action: 0},
        {pageName: 'RESTAURANTLOANANDREPAYVIEW', action: 0},
        {pageName: 'PAYMENTBATCH', action: 0},
        {pageName: 'VENDORMAINTENANCE', action: 0},
        {pageName: 'EXPENSEVIEW', action: 0},
        {pageName: 'PRINTINVOICEBATCH', action: 0},
        {pageName: 'EXPENSEAPPLICATIONVIEW', action: 0},
        {pageName: 'BUDGET', action: 0},
        {pageName: 'BUDGETJOURNAL', action: 0},
        {pageName: 'BUDGETJOURNALREVIEW', action: 0},
        {pageName: 'BUDGETAMOUNT', action: 0},
        {pageName: 'BUDGETBALANCEPLANINQUIRY', action: 0},
        {pageName: 'BUDGETOCCUPANCYADJUSTMENT', action: 0},
        {pageName: 'PAY', action: 0},
        {pageName: 'PAYMENTCENTER', action: 0},
      ],
      pageRoles: [],
      isEdit: false, //是否是编辑状态
      secondDisabled: true, //二级导航是否可编辑
      secondBudgetDisabled: true, //预算的二级导航是否可编辑
      secondPayDisabled: true,//支付的二级导航是否可编辑
      thirdDisabled: true, //三级导航是否可编辑
    }
  }

  componentDidMount() {
    const { defaultData } = this.state;
    if(this.checkFunctionProfiles('all.payment.platform',true,false)){
      defaultData.push({first: {pageName: 'PAY', label: messages('setting.key925'/*支付*/), action: 0},
        second: {pageName: 'PAYMENTCENTER', label: messages('setting.key926'/*付款工作台*/), action: 0}});
    }else{
      defaultData.splice(1,0,{second: {pageName: 'EXPENSEPAYMENT', label: messages('setting.key927'/*确认付款*/), action: 0}},{second: {pageName: 'PAYMENTBATCH', label: messages('setting.key928'/*付款批次*/), action: 0}});
    };
    this.setState({
      data: deepCopy(defaultData),
      pageRoles: deepCopy(this.state.defaultPageRoles)
    }, () => {
      this.setColumns();
      this.getPageRoles()
    })
  }

  getPageRoles = () => {
    let roleOID = this.props.roleOID;
    RSService.getFinanceRoleDetail(roleOID).then(res => {
      //给一个默认值
      let pageRoles = [
        {"roleOID":roleOID,"pageName":"RESTAURANTLOANANDREPAYVIEW","action":0},
        {"roleOID":roleOID,"pageName":"REPAYMENTSLIPMANAGEMENT","action":0},
        {"roleOID":roleOID,"pageName":"FINANCEMANAGEMENT","action":0},
        {"roleOID":roleOID,"pageName":"LOANGLOBALVIEW","action":0},
        {"roleOID":roleOID,"pageName":"PAYMENTBATCH","action":0},
        {"roleOID":roleOID,"pageName":"BUDGETAMOUNT","action":0},
        {"roleOID":roleOID,"pageName":"RECEIPTEDINVOICES","action":0},
        {"roleOID":roleOID,"pageName":"EXPENSEAPPLICATIONVIEW","action":0},
        {"roleOID":roleOID,"pageName":"EXPENSEVIEW","action":0},
        {"roleOID":roleOID,"pageName":"VENDORMAINTENANCE","action":0},
        {"roleOID":roleOID,"pageName":"LOANBILLMANAGEMENT","action":0},
        {"roleOID":roleOID,"pageName":"BUDGETJOURNALREVIEW","action":0},
        {"roleOID":roleOID,"pageName":"EXPENSEPAYMENT","action":0},
        {"roleOID":roleOID,"pageName":"BUDGETOCCUPANCYADJUSTMENT","action":0},
        {"roleOID":roleOID,"pageName":"EXPENSEAUDIT","action":0},
        {"roleOID":roleOID,"pageName":"PRINTINVOICEBATCH","action":0},
        {"roleOID":roleOID,"pageName":"BUDGETJOURNAL","action":0},
        {"roleOID":roleOID,"pageName":"VENDORRECONCILIATION","action":0},
        {"roleOID":roleOID,"pageName":"BUDGET","action":0},
        {"roleOID":roleOID,"pageName":"BUDGETBALANCEPLANINQUIRY","action":0},
        {"roleOID":roleOID,"pageName":"LOANMANAGEMENT","action":0},
        {"roleOID":roleOID,"pageName":"PAY","action":0},
        {"roleOID":roleOID,"pageName":"PAYMENTCENTER","action":0}
      ];
      res.data.pageRoles.map(item => {
        pageRoles.map((roleItem, index) => {
          if (item.pageName === roleItem.pageName) {
            pageRoles[index].action = item.action
          }
        })
      });
      this.setState({
        pageRoles: pageRoles,
        defaultPageRoles: deepCopy(pageRoles)
      }, () => {
        this.setData(this.state.pageRoles)
      })
    })
  };

  //设置表格的列
  setColumns = () => {
    let isPlatform = this.checkFunctionProfiles('all.payment.platform',true,false);
    let columns = [
      {title: messages('setting.key929'/*一级导航*/), dataIndex: 'first', width: '33%', render: (value, record, index) => {
          let showValue = {
            children: value && (
              <div className="col-container">
                {value.label}
                {this.state.isEdit ? (
                  <Select value={value.action}
                          className={this.props.language.locale === 'en' ? "auth-select-en" : "auth-select"}
                          size="small"
                          onChange={action => this.handleAuthChange(value.pageName, action)}
                  >
                    <Option value={0}>{messages('setting.key930'/*无权限*/)}</Option>
                    <Option value={1}>{messages('setting.key931'/*只读*/)}</Option>
                    <Option value={2}>{messages('setting.key932'/*可操作*/)}</Option>
                  </Select>
                ) : (
                  <span className="auth">
                  {value.action === 0 ? messages('setting.key930'/*无权限*/) :
                    (value.action === 1 ? messages('setting.key931'/*只读*/) : messages('setting.key932'/*可操作*/))}
                </span>
                )}
              </div>
            ),
            props: {}
          };
          showValue.props.rowSpan = 0;
          if(isPlatform){
            index === 0 && (showValue.props.rowSpan = 10);
            index === 10 && (showValue.props.rowSpan = 5);
            index === 15 && (showValue.props.rowSpan = 1);
          }else{
            index === 0 && (showValue.props.rowSpan = 12);
            index === 12 && (showValue.props.rowSpan = 5);
          }
          return showValue
        }},
      {title: messages('setting.key933'/*二级导航*/), dataIndex: 'second', width: '34%', render: (value, record, index) => {
          let showValue = {
            children: value && (
              <div className="col-container">
                {value.label}
                {this.state.isEdit ? (
                  <Select value={value.action}
                          className={this.props.language.locale === 'en' ? "auth-select-en" : "auth-select"}
                          size="small"
                          disabled={index < (isPlatform ? 10 : 12) ? this.state.secondDisabled : ( (isPlatform ? index !== 15 : index !== 17) ? this.state.secondBudgetDisabled : this.state.secondPayDisabled)}
                          onChange={action => this.handleAuthChange(value.pageName, action)}
                  >
                    <Option value={0}>{messages('setting.key930'/*无权限*/)}</Option>
                    <Option value={1}>{messages('setting.key931'/*只读*/)}</Option>
                    <Option value={2}>{messages('setting.key932'/*可操作*/)}</Option>
                  </Select>
                ) : (
                  <span className="auth">
                  {value.action === 0 ? messages('setting.key930'/*无权限*/) :
                    (value.action === 1 ? messages('setting.key931'/*只读*/) : messages('setting.key932'/*可操作*/))}
                </span>
                )}
              </div>
            ),
            props: {}
          };
          if(isPlatform){
            if (index === 3)  showValue.props.rowSpan = 3;
            if (index === 4 || index === 5)  showValue.props.rowSpan = 0;
          }else{
            if (index === 5)  showValue.props.rowSpan = 3;
            if (index === 6 || index === 7)  showValue.props.rowSpan = 0;
          }
          return showValue
        }},
      {title: messages('setting.key934'/*三级导航*/), dataIndex: 'third', width: '33%', render: (value, record, index) => {
          let showValue = {
            children: value && (
              <div className="col-container">
                {value.label}
                {this.state.isEdit ? (
                  <Select value={value.action}
                          className={this.props.language.locale === 'en' ? "auth-select-en" : "auth-select"}
                          size="small"
                          disabled={this.state.thirdDisabled}
                          onChange={action => this.handleAuthChange(value.pageName, action)}
                  >
                    <Option value={0}>{messages('setting.key930'/*无权限*/)}</Option>
                    <Option value={1}>{messages('setting.key931'/*只读*/)}</Option>
                    <Option value={2}>{messages('setting.key932'/*可操作*/)}</Option>
                  </Select>
                ) : (
                  <span className="auth">
                  {value.action === 0 ? messages('setting.key930'/*无权限*/) :
                    (value.action === 1 ? messages('setting.key931'/*只读*/) : messages('setting.key932'/*可操作*/))}
                </span>
                )}
              </div>
            ),
            props: {}
          };
          showValue.props.rowSpan = 0;
          if(isPlatform){
            (index === 0) && (showValue.props.rowSpan = 3);
            (index === 3 || index === 4 || index === 5 || index === 17) && (showValue.props.rowSpan = 1);
            (index === 6) && (showValue.props.rowSpan = 4);
            (index === 10) && (showValue.props.rowSpan = 5);
          }else{
            (index === 0) && (showValue.props.rowSpan = 5);
            (index === 5 || index === 6 || index === 7) && (showValue.props.rowSpan = 1);
            (index === 8) && (showValue.props.rowSpan = 4);
            (index === 12) && (showValue.props.rowSpan = 5);
          }
          return showValue
        }}
    ];
    this.setState({ columns })
  };

  //设置表格的权限值
  setData = (pageRoles) => {
    let isPlatform = this.checkFunctionProfiles('all.payment.platform',true,false);
    let data = this.state.data;
    pageRoles && pageRoles.map(item => {
      if(isPlatform){
        switch(item.pageName) {
          case 'FINANCEMANAGEMENT':
            this.setState({ secondDisabled: !item.action });
            data[0].first.action = item.action || 0;
            break;
          case 'EXPENSEAUDIT':
            data[0].second.action = item.action || 0;
            break;
          case 'RECEIPTEDINVOICES':
            data[1].second.action = item.action || 0;
            break;
          case 'VENDORRECONCILIATION':
            data[2].second.action = item.action || 0;
            break;
          case 'LOANMANAGEMENT':
            this.setState({ thirdDisabled: !item.action });
            data[3].second.action = item.action || 0;
            break;
          case 'LOANGLOBALVIEW':
            data[3].third.action = item.action || 0;
            break;
          case 'REPAYMENTSLIPMANAGEMENT':
            data[4].third.action = item.action || 0;
            break;
          case 'LOANBILLMANAGEMENT':
            data[5].third.action = item.action || 0;
            break;
          case 'VENDORMAINTENANCE':
            data[6].second.action = item.action || 0;
            break;
          case 'EXPENSEVIEW':
            data[7].second.action = item.action || 0;
            break;
          case 'PRINTINVOICEBATCH':
            data[8].second.action = item.action || 0;
            break;
          case 'EXPENSEAPPLICATIONVIEW':
            data[9].second.action = item.action || 0;
            break;
          case 'BUDGET':
            data[10].first.action = item.action || 0;
            break;
          case 'BUDGETJOURNAL':
            data[10].second.action = item.action || 0;
            break;
          case 'BUDGETJOURNALREVIEW':
            data[11].second.action = item.action || 0;
            break;
          case 'BUDGETAMOUNT':
            data[12].second.action = item.action || 0;
            break;
          case 'BUDGETBALANCEPLANINQUIRY':
            data[13].second.action = item.action || 0;
            break;
          case 'BUDGETOCCUPANCYADJUSTMENT':
            data[14].second.action = item.action || 0;
            break;
          case 'PAY':
            this.setState({ secondPayDisabled: !item.action });
            data[15].first.action = item.action || 0;
            break;
          case 'PAYMENTCENTER':
            data[15].second.action = item.action || 0;
            break;
          case 'RESTAURANTLOANANDREPAYVIEW':
            data[16].third.action = item.action || 0;
            break;
        }
      }else{
        switch(item.pageName) {
          case 'FINANCEMANAGEMENT':
            this.setState({ secondDisabled: !item.action });
            data[0].first.action = item.action || 0;
            break;
          case 'EXPENSEAUDIT':
            data[0].second.action = item.action || 0;
            break;
          case 'EXPENSEPAYMENT':
            data[1].second.action = item.action || 0;
            break;
          case 'PAYMENTBATCH':
            data[2].second.action = item.action || 0;
            break;
          case 'RECEIPTEDINVOICES':
            data[3].second.action = item.action || 0;
            break;
          case 'VENDORRECONCILIATION':
            data[4].second.action = item.action || 0;
            break;
          case 'LOANMANAGEMENT':
            this.setState({ thirdDisabled: !item.action });
            data[5].second.action = item.action || 0;
            break;
          case 'LOANGLOBALVIEW':
            data[5].third.action = item.action || 0;
            break;
          case 'REPAYMENTSLIPMANAGEMENT':
            data[6].third.action = item.action || 0;
            break;
          case 'LOANBILLMANAGEMENT':
            data[7].third.action = item.action || 0;
            break;
          case 'VENDORMAINTENANCE':
            data[8].second.action = item.action || 0;
            break;
          case 'EXPENSEVIEW':
            data[9].second.action = item.action || 0;
            break;
          case 'PRINTINVOICEBATCH':
            data[10].second.action = item.action || 0;
            break;
          case 'EXPENSEAPPLICATIONVIEW':
            data[11].second.action = item.action || 0;
            break;
          case 'BUDGET':
            data[12].first.action = item.action || 0;
            break;
          case 'BUDGETJOURNAL':
            data[12].second.action = item.action || 0;
            break;
          case 'BUDGETJOURNALREVIEW':
            data[13].second.action = item.action || 0;
            break;
          case 'BUDGETAMOUNT':
            data[14].second.action = item.action || 0;
            break;
          case 'BUDGETBALANCEPLANINQUIRY':
            data[15].second.action = item.action || 0;
            break;
          case 'BUDGETOCCUPANCYADJUSTMENT':
            data[16].second.action = item.action || 0;
            break;
          case 'RESTAURANTLOANANDREPAYVIEW':
            data[17].third.action = item.action || 0;
            break;
        }
      }
    });
    this.setState({ data, defaultData: deepCopy(data) })
  };

  //编辑／取消编辑
  handleAuthEdit = (flag) => {
    let { secondDisabled, secondBudgetDisabled, thirdDisabled, secondPayDisabled } = this.state;
    this.state.defaultPageRoles.map(item => {
      if (item.pageName === 'FINANCEMANAGEMENT') {
        secondDisabled = !item.action;
        thirdDisabled = false;
      }
      if (item.pageName === 'LOANMANAGEMENT') {
        thirdDisabled = !item.action
      }
      if (item.pageName === 'BUDGET') {
        secondBudgetDisabled = !item.action
      }
      if (item.pageName === 'PAY') {
        secondPayDisabled = !item.action
      }
    });
    this.setState({
      isEdit: flag,
      data: deepCopy(this.state.defaultData),
      pageRoles: deepCopy(this.state.defaultPageRoles),
      secondDisabled,
      secondBudgetDisabled,
      secondPayDisabled,
      thirdDisabled
    }, () => {
      this.setColumns()
    })
  };

  //选择权限修改
  handleAuthChange = (pageName, action) => {
    let data = this.state.data;
    let pageRoles = this.state.pageRoles;
    let isPlatform = this.checkFunctionProfiles('all.payment.platform',true,false);
    let indexNum = isPlatform ? 10 : 12;
    let secondNum = isPlatform ? 14 : 16;
    data.map((item, index) => {
      Object.keys(item).map(key => {
        item[key].pageName === pageName && (data[index][key].action = action)
      })
    });
    pageRoles.map((item, index) => {
      if (item.pageName === pageName) {
        pageRoles[index].action = action
      }
    });
    if (pageName === 'FINANCEMANAGEMENT') { //财务管理
      this.setState({ secondDisabled: !action });
      action === 0 && this.setState({ thirdDisabled: !action });
      action === 0 && data.map((item, index) => {
        if (index < indexNum) {
          data[index].second && (data[index].second.action = 0);
          data[index].third && (data[index].third.action = 0);
          pageRoles.map((role, index) => {
            item.second && role.pageName === item.second.pageName && (pageRoles[index].action = 0);
            item.third && role.pageName === item.third.pageName && (pageRoles[index].action = 0)
          })
        }
      })
    }
    if (pageName === 'LOANMANAGEMENT') { //借还款管理
      this.setState({ thirdDisabled: !action });
      action === 0 && data.map((item, index) => {
        data[index].third && (data[index].third.action = 0);
        pageRoles.map((role, index) => {
          item.third && role.pageName === item.third.pageName && (pageRoles[index].action = 0)
        })
      })
    }
    if (pageName === 'BUDGET') { //预算
      this.setState({ secondBudgetDisabled: !action });
      action === 0 && data.map((item, index) => {
        if ((index >= indexNum) && (index <= secondNum)) {
          data[index].second && (data[index].second.action = 0);
          pageRoles.map((role, index) => {
            item.second && role.pageName === item.second.pageName && (pageRoles[index].action = 0);
          })
        }
      })
    }
    if (pageName === 'PAY') { //支付
      this.setState({ secondPayDisabled: !action });
      action === 0 && data.map((item, index) => {
        if (index === 15) {
          data[index].second && (data[index].second.action = 0);
          pageRoles.map((role, index) => {
            item.second && role.pageName === item.second.pageName && (pageRoles[index].action = 0);
          })
        }
      })
    }
    this.setState({ data, pageRoles }, () => {
      this.setColumns()
    })
  };

  handleSave = () => {
    this.setState({ loading: true });
    let pageRoles = this.state.pageRoles;
    pageRoles.map((item, index) => {
      pageRoles[index].roleOID = this.props.roleOID
    });
    RSService.saveFinancePageAuth(pageRoles).then(res => {
      this.setState({
        loading: false,
        pageRoles: res.data,
        defaultData: deepCopy(this.state.data),
        defaultPageRoles: deepCopy(res.data)
      });
      this.handleAuthEdit(false);
      baseService.getUser()
    }).catch(() => {
      this.setState({ loading: false })
    })
  };

  render() {
    const { roleBaseInfo } = this.props;
    const { loading, columns, data, isEdit } = this.state;
    return (
      <div className="detail-page-auth">
        {/*系统预设角色不可编辑页面权限*/}
        {roleBaseInfo.roleID !== 'SuperAud' && roleBaseInfo.roleID !== 'SuperFin' && (
          <div className="table-header">
            <div className="table-header-buttons">
              {isEdit ? (
                <div>
                  <Button type="primary" onClick={this.handleSave} loading={loading}>{messages('common.save')}</Button>
                  <Button onClick={() => {this.handleAuthEdit(false)}}>{messages('common.cancel')}</Button>
                </div>
              ) : <Button type="primary" onClick={() => {this.handleAuthEdit(true)}}>{messages('common.edit')}</Button>}
            </div>
          </div>
        )}
        <ResizeTable
          rowKey={(record, index) => index}
          columns={columns}
          dataSource={data}
          pagination={{pageSize: 20}}
          size="middle"
          bordered
        />
      </div>
    )
  }
}

DetailPageAuth.propTypes = {
  pageRoles: React.PropTypes.array,
  roleBaseInfo: React.PropTypes.object,
  roleOID: React.PropTypes.string,
};

DetailPageAuth.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    language: state.main.language
  }
}

const wrappedDetailPageAuth = Form.create()(DetailPageAuth);

export default connect(mapStateToProps)(wrappedDetailPageAuth)
